import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/login_init_dao.dart';
import 'package:changxindianzishangwu/dao/sms_code_dao.dart';
import 'package:changxindianzishangwu/db/ec_cache.dart';
import 'package:changxindianzishangwu/http/base/http_urls.dart';
import 'package:changxindianzishangwu/model/base_model.dart';
import 'package:changxindianzishangwu/model/user_info_model.dart';
import 'package:changxindianzishangwu/model/we_chat_user_info_model.dart';
import 'package:changxindianzishangwu/pages/home_page.dart';
import 'package:changxindianzishangwu/pages/login/login_update_info_page.dart';
import 'package:changxindianzishangwu/provider/user.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/app_string.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:changxindianzishangwu/widget/app_bar.dart';
import 'package:changxindianzishangwu/widget/icon_text_button.dart';
import 'package:changxindianzishangwu/widget/web_view.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';
import 'package:tpns_flutter_plugin/tpns_flutter_plugin.dart';

import 'country_phone_page.dart';
import 'login_binding_account_page.dart';

///三方登录=》绑定手机号
class LoginBindingPhonePage extends StatefulWidget {
  WeChatUserInfoModel weChatUserInfoModel;

  LoginBindingPhonePage({
    this.weChatUserInfoModel,
    Key key,
  }) : super(key: key);

  @override
  _LoginBindingPhonePageState createState() => _LoginBindingPhonePageState();
}

class _LoginBindingPhonePageState extends State<LoginBindingPhonePage> {
  TextEditingController _controller;
  TextEditingController _controllerPwd;
  FocusNode focusNode = FocusNode(); //密码框焦点

  TimerUtil _timeUtil;

  int _totalTime = 60;
  int _time = 0;

  @override
  void initState() {
    // TODO: implement initState
    _controller = TextEditingController();
    _controllerPwd = TextEditingController();
    super.initState();
    _timeUtil = TimerUtil(mTotalTime: _totalTime);
    _timeUtil.setOnTimerTickCallback((millisUntilFinished) {
      setState(() {
        _time = _totalTime - millisUntilFinished;
        if (_time == 0) {
          _timeUtil.cancel();
        }
      });
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    _controllerPwd.dispose();
    _timeUtil.cancel();
    // TODO: implement dispose
    EasyLoading.dismiss();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Scaffold(
        appBar: TopAppBar(context, ""),
        body: SingleChildScrollView(
          child: Container(
            constraints: BoxConstraints(
                maxHeight: MediaQuery.of(context).size.height - 45),
            color: Colors.white,
            padding: EdgeInsets.all(15),
            child: _content(),
          ),
        ),
      ),
    );
  }

  Column _content() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text("绑定手机号", style: _styleTv(18, AppColor.colorDefaultText)),
        Padding(
          padding: const EdgeInsets.only(top: 10, bottom: 30),
          child: Text(
            "${AppString.bindingPhoneHint}",
            style: _styleTv(15, AppColor.colorGrey153),
          ),
        ),
        Text(
          "手机号码",
          style: _styleTv(15, AppColor.colorText85),
        ),
        Padding(
          padding: const EdgeInsets.only(top: 13),
          child: Container(
            child: Row(
              children: <Widget>[
                InkWell(
                  onTap: () {
                    _goTo();
                  },
                  child: Row(
                    children: [
                      Text(
                        phoneCountry,
                        style: _styleTv(16, AppColor.colorText85),
                      ),
                      SizedBox(
                        width: width(8),
                      ),
                      Image.asset("images/下拉.png"),
                    ],
                  ),
                ),
                SizedBox(
                  width: width(10),
                ),
                Expanded(
                  child: TextField(
                    maxLines: 1,
                    keyboardType: TextInputType.number,
                    cursorColor: Colors.greenAccent,
                    controller: _controller,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: "请输入新手机号码",
                      hintStyle: TextStyle(
                        fontSize: sp(13),
                        color: Color.fromRGBO(153, 153, 153, 1),
                      ),
                    ),
                    inputFormatters: [
                      LengthLimitingTextInputFormatter(13), //最大长度
                    ],
                    onTap: () {
                      FocusScope.of(context).requestFocus(focusNode);
                    },
                    focusNode: focusNode,
                  ),
                ),
              ],
            ),
          ),
        ),
        UniversalView().line(),
        Padding(
          padding: const EdgeInsets.only(top: 15),
          child: Text(
            "验证码",
            style: _styleTv(15, AppColor.colorText85),
          ),
        ),

        Padding(
          padding: const EdgeInsets.only(top: 10),
          child: Row(
            children: [
              Expanded(
                flex: 1,
                child: TextField(
                  controller: _controllerPwd,
                  keyboardType: TextInputType.number,
                  cursorColor: Colors.greenAccent,
                  decoration: InputDecoration(
                    border: InputBorder.none,
                    hintText: "请输入验证码",
                    hintStyle: TextStyle(
                      fontSize: sp(13),
                      color: Color.fromRGBO(153, 153, 153, 1),
                    ),
                  ),
                ),
              ),
              TextButton(
                  onPressed: () {
                    String _phone = _controller.text.toString().trim();
                    if (_phone.length < 7) {
                      showToast("请输入正确的手机号");
                      return;
                    }
                    if (_phone.length > 11) {
                      showToast("请输入正确的手机号");
                      return;
                    }
                    if (_time == 0) _getSmsCode(_phone);
                  },
                  child: Text(
                    _time == 0 ? "获取验证码" : "${_time}s后重新获取",
                    style: _styleTv(13, AppColor.colorTheme),
                  ))
            ],
          ),
        ),
        UniversalView().line(),

        Padding(
          padding: const EdgeInsets.only(top: 40),
          child: UniversalView().longBtn("绑定", () {
            print('${_controllerPwd.text}');
            String account = _controller.text.toString().trim();
            String code = _controllerPwd.text.toString().trim();
            if (account.isEmpty) {
              toast("请输入手机号");
              return;
            }
            if (account.length < 7) {
              showToast("请输入正确的手机号");
              return;
            }
            if (account.length > 11) {
              showToast("请输入正确的手机号");
              return;
            }
            if (code.isEmpty) {
              toast("请输入验证码");
              return;
            }
            _bindingUser(account, code);
          }),
        ),
        // Expanded(
        //   child: SizedBox(),
        //   flex: 1,
        // ),
        SizedBox(
          height: height(30),
        ),
        Center(
          child: Text.rich(TextSpan(children: [
            TextSpan(
                text: "无法接收验证码？", style: _styleTv(12, AppColor.colorGrey153)),
            _textUrl("使用账号绑定", HttpUrls.YH_XY),
          ])),
        )
      ],
    );
  }

  _textUrl(String title, url) {
    return TextSpan(
        text: title,
        style: TextStyle(color: AppColor.colorTheme, fontSize: sp(12)),
        recognizer: new TapGestureRecognizer()
          ..onTap = () {
            Get.to(LoginBindingAccountPage(widget.weChatUserInfoModel));
          });
  }

  TextStyle _styleTv(double size, color) {
    return TextStyle(fontSize: sp(size), color: color);
  }

  void _bindingUser(account, code) async {
    EasyLoading.show();

    var _userinfoModel = await LoginInitDao.loginBindingPhone(widget.weChatUserInfoModel, account, code,
        areaCode: phoneCountry.substring(1, phoneCountry.length));
    if (_userinfoModel is BaseModel) {
      _hideLoading();
      toast("绑定错误：${_userinfoModel.resultMsg}");
      return;
    }
    _loginIm(_userinfoModel);
  }

  _loginIm(_userinfoModel) {
    TencentImSDKPlugin.v2TIMManager
        .login(
      userID: _userinfoModel.data.userId,
      userSig: _userinfoModel.data.userSig,
    )
        .then((res) async {
      _hideLoading();

      if (res.code == 0) {
        getData();
        final XgFlutterPlugin tpush = new XgFlutterPlugin();
        tpush.setAccount(getUserId(), AccountType.UNKNOWN);
        showToast("登录成功");
        return _userinfoModel.data.isFirstIn == 1
            ? Get.offAllNamed(
                "/homePage",
                arguments: getAppLoginToken(),
              )
            : Get.offAll(LoginUpdateInfoPage(
                weChatUserInfoModel: widget.weChatUserInfoModel,
                isQr: true,
              ));
      }else{
        showToast("IM 登录失败");

      }
    });
  }

  String phoneCountry = "+86";

  _goTo() {
    Get.to(() => CountryPhonePage()).then((value) {
      if (value == null) {
        phoneCountry = "+86";
      } else {
        try {
          phoneCountry = value;
        } catch (e) {
          print(e);
        }
      }
    });
  }

  getData() async {
    V2TimValueCallback<List<V2TimUserFullInfo>> infos = await TencentImSDKPlugin
        .v2TIMManager
        .getUsersInfo(userIDList: [EcCache.getInstance().get('userId')]);
    if (infos.code == 0) {
      Provider.of<UserModel>(context, listen: false).setInfo(infos.data[0]);
    }
  }

  void _hideLoading() {
    EasyLoading.dismiss();
  }

  _getSmsCode(phone) async {
    EasyLoading.show();
    var result = await SmsCodeDao.getCode(
        phone, phoneCountry.substring(1, phoneCountry.length), FORGET_PASSWORD);
    EasyLoading.dismiss();
    if (result['resultCode'] != 1) {
      toast("获取验证码失败：${result["resultMsg"]}");
      return;
    }
    _timeUtil.startTimer();
    toast("获取验证码成功");
  }
}
